package angry.courses.servlets;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import java.io.IOException;

import javax.servlet.ServletException;

public class AddCourseServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws  ServletException, IOException {
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();

		out.println(new HtmlFormatter() {
			public String title() {
				return "Add Course";
			}

			public void body(StringBuffer buf) {
				buf.append(heading(3,
				   "Specify the details for the new course:"));
				buf.append("<form method=\"post\" action=\"AddCourse\">");
				buf.append("<table>");
		
				buf.append(tr("Course name:", textbox("name")));
				buf.append(tr("Professor name:", textbox("prof")));
				buf.append(tr("Year: " + dropdown("year", "", "1", "2", "3", "4"),
					"Semester: " + dropdown("sem", "", "I", "II")));
				buf.append("</table>");
				buf.append(button("Submit"));
				buf.append("<form/>");
			}
		}.htmlTag());
		out.close();
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		final String name = req.getParameter("name");
		final String prof = req.getParameter("prof");
		final int year = Integer.parseInt(req.getParameter("year"));
		final int sem = req.getParameter("sem").equals("I") ? 1 : 2;

		CourseDelegate courseDelegate = new CourseDelegate();
		courseDelegate.createCourse(name, year, sem, prof);

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		out.println(new HtmlFormatter() {
			public String title() {
				return "Course added";
			}
	    
            public void body(StringBuffer buf) {
				buf.append(heading(3, "Completed"));
				buf.append("The course was added successfully.<br>");
				buf.append("Click " + link("here", "admin.html") +
					   " to go back.");
			}
		}.htmlTag());
		out.close();    
    }
}
